﻿using System;
using System.Web;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using kysec.RAL.EFToMySql;
using MySql.Data.MySqlClient;
namespace kysec.Bll.Message
{
    /// <summary>
    /// 查找留言回复信息
    /// </summary>
    public class Sreach {
        /// <summary>
        /// 查找所有的留言回复
        /// </summary>
        /// <param name="mId">回复的留言Id</param>
        /// <param name="takeitem">每页显示几页</param>
        /// <param name="page">跳过几页</param>
        /// <returns>返回找到的列表</returns>
        public static List<tb_message_replay> getAllReplayMsg(string id,int takeitem,int page)
        { 
            Guid mId = Guid.Parse(kysec.CR.Common.EncodeByBase64.Decode(id));
            var o = kysec.CR.Cache.CacheManage.DefaultStrategy.GetEntity() // 从Cache中读取信息
                          .RetrieveObject(string.Format("getAllReplayMsg_{0}_{1}_{2}", mId
                           , page, takeitem));
            if (o == null)
            {
                MySql_kysecContectionString ctx = new MySql_kysecContectionString();
              
                //找出所有的留言信息
                var str = from c in ctx.tb_message_replay
                          where c.c_b_isDelete == false
                          orderby c.c_dt_replayTime descending
                          select c;

                //找出是否已被操作的留言信息：true：已回复 和 false：未回复
                if (mId != null)
                {
                    str = from c in ctx.tb_message_replay
                          where c.c_b_isDelete == false  && c.c_uq_mId.Equals(mId.ToString())
                          orderby c.c_dt_replayTime descending
                          select c;
                }

                var list = (str).Skip(takeitem * page)
                             .Take(takeitem)
                             .ToList();
                ctx.Dispose();
                if (list.Any())
                {
                    kysec.CR.Cache.CacheManage.DefaultStrategy.GetEntity()
                      .AddObjectWithAbsoluteTime(string.Format("getAllReplayMsg_{0}_{1}_{2}", mId,page, takeitem)
                      , list,
                      10000
                      , System.Web.Caching.CacheItemPriority.Normal);
                    return list;
                }
                return new List<tb_message_replay>();
            }
            return (List<tb_message_replay>)o;
        }
    }
    /// <summary>
    /// 留言回复信息操作类
    /// </summary>
    public class msg_replay
    {
        /// <summary>
        /// 添加留言时就给回复表中添加信息
        /// </summary>
        /// <param name="mId">留言的ID</param>
        /// <returns>返回1：添加成功，0：失败，2：异常</returns>
        public static string AddReplayMsg(Guid mId)
        {
            string result = "0";

            MySql_kysecContectionString ctx = new MySql_kysecContectionString();

            try
            {
                tb_message_replay replayMsg = new tb_message_replay {
                    c_uq_mId = mId.ToString(),
                    c_uq_mrId = Guid.NewGuid().ToString(),
                    c_b_isDelete = false
                };
                ctx.AddObject("tb_message_replay", replayMsg);
                result = ctx.SaveChanges().ToString();
            }
            catch (Exception ex)
            {
                string error = ex.ToString() + "\t插入回复留言信息初始化时出错";
                kysec.CR.Logger.MyLogger.Error(typeof(message), error);
                result = "2";
            }
            finally { ctx.Dispose(); }
            return result;
        }

        /// <summary>
        /// 添加回复信息
        /// </summary>
        /// <param name="id">需要回复的ID</param>
        /// <param name="model">回复的内容</param>
        /// <returns>1：成功 0：失败 2：异常</returns>
        public static string UpdateReplayMsg(string id, tb_message_replay model)
        {
            string result = "0";

            MySql_kysecContectionString ctx = new MySql_kysecContectionString();
            id = kysec.CR.Common.EncodeByBase64.Decode(id);

            try
            {
                var list = ctx.tb_message_replay.Where(c => c.c_uq_mId.Equals(id) && c.c_b_isDelete == false).ToList();
                if (list.Count == 0)
                    result = "0";
                else
                {
                    foreach (var item in list)
                    {
                        item.c_dt_replayTime = DateTime.Now;
                        item.c_ntx_content = model.c_ntx_content;
                    }
                    if (isFinishReplay(id))
                    {
                        result = ctx.SaveChanges().ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                string error = ex.ToString() + "\t添加回复信息时出错";
                kysec.CR.Logger.MyLogger.Error(typeof(message), error);
                result = "2";
            }
            finally { ctx.Dispose(); }
            return result;
        }

        /// <summary>
        /// 判断留言已回复的标志
        /// </summary>
        /// <param name="mId">留言Id</param>
        /// <returns>ture：成功 false：失败</returns>
        public static bool isFinishReplay(string mId)
        {
            bool result = false;
            MySql_kysecContectionString ctx = new MySql_kysecContectionString();

            try
            {
                var list = ctx.tb_message.Where(c => c.c_uq_mId.Equals(mId) && c.c_b_isDelete == false).ToList();
                if (list.Count != 0)
                {
                    foreach (var item in list)
                    {
                        item.c_b_isReplay = true;
                    }
                    result = ctx.SaveChanges() == 1 ? true : false;
                }
            }
            catch (Exception ex)
            {
                string error = ex.ToString() + "\t留言已回复";
                kysec.CR.Logger.MyLogger.Error(typeof(message), error);
            }
            finally { ctx.Dispose(); }
            return result;
        }

        /// <summary>
        /// 删除留言信息，可以同时恢复删除的留言
        /// </summary>
        /// <param name="newsId">需要删除的留言信息的Id</param>
        /// <returns>0：没有找到信息或删除失败 1：删除成功 2：删除异常</returns>
        public static string DeleteMessage(string mmrid)
        {
            string result = "0";

            MySql_kysecContectionString ctx = new MySql_kysecContectionString();

            try
            {
                mmrid = kysec.CR.Common.EncodeByBase64.Decode(mmrid);
                var list = ctx.tb_message_replay.Where(c => c.c_uq_mrId.Equals(mmrid)).ToList();

                if (list.Count == 0)
                    result = "0";
                else
                {
                    foreach (var item in list)
                    {
                        if (item.c_b_isDelete)
                            item.c_b_isDelete = false;
                        else
                            item.c_b_isDelete = true;
                    }
                    result = ctx.SaveChanges().ToString();
                    result = "1";
                }
            }
            catch (Exception ex)
            {
                string error = ex.ToString() + "\t删除回复留言信息时出错";
                kysec.CR.Logger.MyLogger.Error(typeof(message), error);
                result = "2";
            }
            finally { ctx.Dispose(); }
            return result;
        }

    }
}
